package de.slothsoft.commons.swing;

import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;

import de.slothsoft.commons.res.CommonImages;
import de.slothsoft.commons.res.CommonMessages;
import de.slothsoft.commons.swing.AboutPanel.AboutInfo;
import de.slothsoft.commons.swing.util.SwingUtil;
import de.slothsoft.commons.swing.window.AboutDialog;
import de.slothsoft.commons.swing.window.ConsoleDialog;

public class JToolBarManager {

	private final JToolBar toolBar;
	private ActionListener defaultActionListener;

	public JToolBarManager() {
		this(new JToolBar());
	}

	public JToolBarManager(JToolBar toolBar) {
		this.toolBar = toolBar;
	}

	public JToolBar getToolBar() {
		return this.toolBar;
	}

	public JButton add(Icon icon, ActionListener listener) {
		return add(icon, null, listener);
	}

	public JButton add(Icon icon, String tooltip, ActionListener listener) {
		JButton button = SwingUtil.createToolBarButton(icon, tooltip);
		if (this.defaultActionListener != null) {
			button.addActionListener(this.defaultActionListener);
		}
		button.addActionListener(listener);
		this.toolBar.add(button);
		return button;
	}

	public JToggleButton addToggle(Icon icon, ActionListener listener) {
		return addToggle(icon, null, listener);
	}

	public JToggleButton addToggle(Icon icon, String tooltip, ActionListener listener) {
		JToggleButton button = SwingUtil.createToolBarToggleButton(icon, tooltip);
		if (this.defaultActionListener != null) {
			button.addActionListener(this.defaultActionListener);
		}
		button.addActionListener(listener);
		this.toolBar.add(button);
		return button;
	}

	public void addSeparator() {
		this.toolBar.addSeparator();
	}

	public ActionListener getDefaultActionListener() {
		return this.defaultActionListener;
	}

	public void setDefaultActionListener(ActionListener defaultActionListener) {
		this.defaultActionListener = defaultActionListener;
	}

	public void addAboutButton(final Window parent, final AboutInfo info) {
		add(CommonImages.get(CommonImages.TOOLBAR_ABOUT),
				CommonMessages.getString("AboutDialog.toolbarButton"), new ActionListener() {//$NON-NLS-1$

					@Override
					public void actionPerformed(ActionEvent e) {
						AboutDialog dialog = new AboutDialog(parent, info);
						dialog.open();
					}
				});
	}

	public void addConsoleButton(final Window parent) {
		add(CommonImages.get(CommonImages.OBJECT_CONSOLE),
				CommonMessages.getString("ConsoleDialog.toolbarButton"), new ActionListener() {//$NON-NLS-1$

					ConsoleDialog dialog = new ConsoleDialog(parent);

					@Override
					public void actionPerformed(ActionEvent e) {
						this.dialog.open();
					}
				});
	}

}
